package com.hmdp.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.*;
import java.util.function.Function;

import static com.hmdp.utils.RedisConstants.CACHE_NULL_TTL;
import static com.hmdp.utils.RedisConstants.LOCK_SHOP_KEY;


@Slf4j
@Component
public class CacheClient {
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);
    private StringRedisTemplate stringRedisTemplate;

    public CacheClient(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    //设置TTL处理缓存击穿
    public void set(String key, Object value, Long time, TimeUnit unit) {
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value),
                time, unit);
    }

    //设置逻辑过期时间处理缓存击穿
    public void setWithLogicalExpire(String key, Object value, Long time, TimeUnit unit) {
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }

    //利用缓存空值方式解决缓存穿透问题
    public <T,ID> T queryWithPassThrough(String keyPrefix, ID id, Class<T> type, Function<ID,T> dbSQL,Long time, TimeUnit unit) {
        String key = keyPrefix + id;

        //从redis查询商铺缓存
        String json = stringRedisTemplate.opsForValue().get(key);

        //判断是否存在
        if (StrUtil.isNotBlank(json)){
            return JSONUtil.toBean(json, type);
        }

        //判断缓存命中是否为空值
        if (json!=null){
            return null;
        }

        //不存在，根据id查询数据库
        T t = dbSQL.apply(id);

        //值为空，将空值写入redis
        if (t == null){
            stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
        }

        //存在，写入redis
        this.set(key, t, time, unit);

        return t;
    }

    //利用逻辑过期解决缓存击穿
    public <T,ID>T queryWithLogicalExpire(String keyPrefix, ID id, Class<T> type, Function<ID,T> dbSQL,Long time, TimeUnit unit) {
        String key = keyPrefix + id;

        //从redis查询缓存
        String json = stringRedisTemplate.opsForValue().get(key);
        //判断缓存是否存在
        if (StrUtil.isBlank(json)){
            return null;
        }

        //命中，把json反序列化为对象
        RedisData redisData = JSONUtil.toBean(json, RedisData.class);
        T t = JSONUtil.toBean((JSONObject) redisData.getData(), type);
        LocalDateTime expireTime = redisData.getExpireTime();

        //判断逻辑时间是否过期
        if (expireTime.isAfter(LocalDateTime.now())){
            return t;
        }

        //过期，需要重建缓存
        //获取互斥锁
        String lockKey = LOCK_SHOP_KEY + id;
        boolean b = tryLock(lockKey);

        //判断是否成功获取锁
        if (b){
            CACHE_REBUILD_EXECUTOR.submit(()->{
               try {
                   T apply = dbSQL.apply(id);
                   this.setWithLogicalExpire(key,apply,time,unit);
               } catch (Exception e){
                   throw new RuntimeException(e);
               } finally {
                   //释放锁
                   unlock(lockKey);
               }
            });
        }

        //返回过期缓存信息
        return t;
    }

    public boolean tryLock(String lockKey) {
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(lockKey,"1",10,TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    public void unlock(String lockKey) {
        stringRedisTemplate.delete(lockKey);
    }
}
